/* 通过接受配置项构造一个处理器 */
const logger = require('./Logger')
const Executor = require('./Executor')

class Handler {
  constructor (params) {
    this._token = params.token
    this._eventMatcher = params.eventMatcher
    this._branchMatcher = params.branchMatcher
    this._executor = params.executor
  }

  handle ({ token }) {
    try {
      if (this._token) {
        if (typeof(token) === 'function' && !token(this._token)) {
          return { code: 'token_not_matched', message: '未传入token或者token不匹配' }
        } else if (token !== this._token) {
          return { code: 'token_not_matched', message: '未传入token或者token不匹配' }
        }
      }
      this._executor.execute() // TODO 需要日志
      return { code: 'success', message: '正常处理' }
    } catch (err) {
      if (err instanceof Executor.ResolveError) {
        return { code: 'execute_error', message: `执行executor插件时出错，${err.message}` }
      } else if (err instanceof Executor.ExecuteError) {
        logger.error('执行executors插件时出现未知错误', err.reason)
        return { code: 'execute_error', message: '执行executor插件时出现未知错误' }
      } else {
        throw err
      }
    }
  }

  match ({ branch, event }) {
    return this._eventMatcher.match(event) && this._branchMatcher.match(branch)
  }
}

Handler.Error = class HandlerError extends Error {}

module.exports = Handler
